<?php

namespace app\api\model;

use think\model\concern\SoftDelete;

class Record extends BaseModel {
    protected $name = 'records';
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    use SoftDelete;
    protected $deleteTime = 'deleted_at';

    public function getAll($params) {
        $size = setParam($params, 'size');
        $page = setParam($params, 'page');
        $map[] = isset($params['order']) ? setWhereOpt($params, 'order') : ['order', '=', 1];
        if (!empty($params['name'])) {
            $map[] = setWhereOpt($params, 'name', 'like');
        }
        if (!empty($params['id_card'])) {
            $map[] = setWhereOpt($params, 'id_card');
        }
//        return self::where($map)->fetchSql(true)->select();
        return self::where($map)->order("id DESC")->paginate([
            'list_rows' => $size,
            'page' => $page

        ]);
    }

    public function getOne($id) {
        return self::where('id', $id)->find();
    }

    public function saveOne($data) {
        $record = self::create($data);
        return $record;
    }

    public function updateOne($data): bool {
        $record = self::where('id', $data['id'])->find();
        return $record->save($data);
    }

    public function deleteOne($id): bool {
        return self::find($id)->delete();
    }

    public function user() {
        return $this->belongsTo(User::class, 'user_id');
    }
}